package com.duofan.gmall.ware.listener;

import com.alibaba.fastjson.JSON;
import com.duofan.gmall.common.to.mq.OrderTo;
import com.duofan.gmall.common.to.mq.StockLockedTo;
import com.duofan.gmall.ware.config.MyRabbitConfig;
import com.duofan.gmall.ware.service.WareSkuService;
import com.duofan.gmall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@RabbitListener(queues = MyRabbitConfig.STOCK_RELEASE_STOCK_QUEUE)
@Service
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedReleae(StockLockedTo to, Message message, Channel channel) throws IOException {
        log.info("接收到库存解锁消息: \n {}", JSON.toJSONString(to, true));
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        log.info("接收到订单关闭消息: \n {}", JSON.toJSONString(orderTo, true));
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch(Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
